<template>
  <div>
    <avue-skeleton v-if="!flowChartsLoading"  avatar :rows="10" :number="1"></avue-skeleton>
    <div id="container"></div>
    
    <div v-for="(subFlowContainer, index) in subFlowInfo.subFlowContainerList" :key="index">
      <el-dialog title="子流程" 
                :width="subFlowInfo.widthList[index]" 
                :modal="false"
                :close-on-click-modal='false' 
                :visible.sync="subFlowInfo.subFlowChartDialogMap[subFlowContainer]"
                @opened="drawSubFlowCharts(subFlowContainer, index)">
        <avue-skeleton v-if="!subFlowInfo.subFlowChartsLoading" avatar :rows="10" :number="1"></avue-skeleton>
        <div :id="subFlowContainer"></div>
        <div slot="footer" class="dialog-footer">
          <el-button  icon="el-icon-close"  size="small" @click="closeSubFlow(subFlowContainer, index)">关闭</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {getFlowChartData} from '@/api/general/flow/generalFlowInfoApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
export default {
  data() {
    return {
      graph: null,
      flowChartsLoading: false,
      oldFlowData: {},
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {},
      subFlowInfo: {
        subFlowChartDialogMap: {
          subFlowContainer0: false,
          subFlowContainer1: false,
          subFlowContainer2: false,
          subFlowContainer3: false,
        },
        subFlowContainerList: ['subFlowContainer0', 'subFlowContainer1', 'subFlowContainer2', 'subFlowContainer3'],
        subFlowData: [],
        graphList: [null, null, null, null],
        subFlowChartsLoading: false,
        widthList: ['75%', '70%','65%', '60%']
      }
    }
  },
  created() { //不能在created方法中初始化
    //this.initG6()
  },
  mounted(){
    // this.initG6()
  },
  methods: {
    /**
     * 获取流程数据
     */
    getFlowChartData(id){
      //this.$console.log('from parent id ====',id)
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      });
      this.reqParams =  {
        singleBody: {
          id: id
        }
      }
      let commonData = reqCommonMsg(this.reqParams)
      getFlowChartData(commonData).then(res => {
        loading.close();
        if(this.oldFlowData != JSON.stringify(res.data.body.flowArea.flowExtData)){
          this.oldFlowData = JSON.stringify(res.data.body.flowArea.flowExtData);
          this.drawFlowCharts(res.data.body.flowArea.flowExtData);
        }
        loading.close();
      }, error => {
        //this.$console.log(error);
        loading.close();
      });
    },
    /**
     * 绘图区
     */
    drawFlowCharts(data){     
      let _self = this;
      if(!this.graph){
        G6.registerNode(
          'sql',
          {
            drawShape(cfg, group) {
              let rect = null;
              if(cfg.isSubFlow == '1'){
                rect = group.addShape('rect', {
                  attrs: {
                    x: -75,
                    y: -25,
                    width: 150,
                    height: 50,
                    radius: 25,
                    stroke: '#5B8FF9',
                    fill: '#B2E98E',
                    lineWidth: 1,
                  },
                  name: 'rect-shape',
                });
              }
              else {
                if(cfg.isBegin){
                  rect = group.addShape('rect', {
                    attrs: {
                      x: -25,
                      y: -25,
                      width: 50,
                      height: 50,
                      radius: 25,
                      stroke: '#5B8F00',
                      fill: '#C6E5FF',
                      lineWidth: 1,
                    },
                    name: 'rect-shape',
                  });
                }
                else if(cfg.isEnd){
                  rect = group.addShape('rect', {
                    attrs: {
                      x: -25,
                      y: -25,
                      width: 50,
                      height: 50,
                      radius: 25,
                      stroke: '#5B8FF9',
                      fill: '#C6E5FF',
                      lineWidth: 1,
                    },
                    name: 'rect-shape',
                  });
                }
                else {
                  rect = group.addShape('rect', {
                    attrs: {
                      x: -75,
                      y: -25,
                      width: 150,
                      height: 50,
                      radius: 10,
                      stroke: '#5B8FF9',
                      fill: '#C6E5FF',
                      lineWidth: 1,
                    },
                    name: 'rect-shape',
                  });
                }
              }
              if (cfg.name) {
                //this.$console.log('cfg===== ',cfg)
                if(parseInt(cfg.id) % 2 == 0)
                {
                  group.addShape('text', {
                    attrs: {
                      text: cfg.name,
                      x: 0,
                      y: 0,
                      fill: '#00287E',
                      fontSize: 14,
                      textAlign: 'center',
                      textBaseline: 'middle',
                      fontWeight: 'bold',
                    },
                    name: 'text-shape',
                  });
                }
                else{
                  group.addShape('text', {
                    attrs: {
                      text: cfg.name,
                      x: 0,
                      y: 0,
                      fill: '#000000',
                      fontSize: 14,
                      textAlign: 'center',
                      textBaseline: 'middle',
                      fontWeight: 'bold',
                    },
                    name: 'text-shape',
                  });
                }
              
              }
              return rect;
            },
          },
          'single-node',
        );
        
        // 点击节点触发
        G6.registerBehavior('click-select', {
          getEvents() {
            return {
              'node:click': 'onNodeClick',
            };
          },
          onNodeClick(evt) {
            // 判断是否是子流程，如果是则打开子流程的流程图
            if(evt.item._cfg.model.isSubFlow === '1' && evt.item._cfg.model.subFlowId){
              // 获取子流程的信息
              //this.$console.log('evt.item._cfg.model.subFlowId ====',evt.item._cfg.model.subFlowId)
              let subFlowId = evt.item._cfg.model.subFlowId;
              const loading = _self.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading'
              });
              let reqParams =  {
                singleBody: {
                  id: subFlowId
                }
              }
              let commonData = reqCommonMsg(reqParams)
              getFlowChartData(commonData).then(res => {
                _self.subFlowInfo.subFlowData.push(res.data.body.flowArea.flowExtData);
                _self.subFlowInfo.subFlowChartDialogMap[_self.subFlowInfo.subFlowContainerList[0]] = true;

                //this.$console.log(_self.subFlowInfo.subFlowData.slice(-1));
                //this.$console.log(_self.subFlowInfo.subFlowData);
                //this.$console.log('subFlowInfo.subFlowChartDialogMap[index]====>', _self.subFlowInfo.subFlowChartDialogMap[_self.subFlowInfo.subFlowContainerList[0]])
                loading.close();
              }, error => {
                //this.$console.log(error);
                loading.close();
              });
            }
          },
        });

        const width = document.getElementById('container').scrollWidth;
        const height = document.getElementById('container').scrollHeight || 400;
        this.graph = new G6.Graph({
          animate: true,
          fitView: true,
          container: 'container',
          width,
          height,
          layout: {
            type: 'dagre',
            rankdir: 'LR',
            align: 'UL',
            nodesepFunc: d => {
              if (d.id === '3') {
                return 100;
              }
              return 50;
            },
            ranksep: 70,
            controlPoints: true
          },
          defaultNode: {
            type: 'sql',
          },
          defaultEdge: {
            type: 'polyline',
            style: {
              radius: 20,
              offset: 45,
              endArrow: true,
              lineWidth: 2,
              stroke: '#C2C8D5',
            },
          },
          nodeStateStyles: {
            selected: {
              stroke: '#d9d9d9',
              fill: '#5394ef',
            }
          },
          modes: {
            default: [
              'drag-canvas',
              'zoom-canvas',
              'click-select',
              {
                type: 'tooltip',
                formatText(model) {
                  const cfg = model.conf;
                  const text = [];
                  cfg.forEach(row => {
                    text.push(row.label + ':' + row.value + '<br>');
                  });
                  return text.join('\n');
                },
                offset: 30
              },
            ],
          }
        });
      }
      this.graph.data(data);
      this.graph.render();
      this.flowChartsLoading = true;
    },

    /**
     * 画子流程
     */
    drawSubFlowCharts(subFlowContainer, index){
      let _self = this;
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      });
      //this.$console.log('index---->', index)
      let data = this.subFlowInfo.subFlowData[index];
      // let subFlowContainer = this.subFlowInfo.subFlowContainerList[index]
      //this.$console.log('data, subFlowContainer------->', data, subFlowContainer)
      if(!this.subFlowInfo.graphList[index]){
        G6.registerNode(
          'sql',
          {
            drawShape(cfg, group) {
              let rect = null;
              if(cfg.isSubFlow == '1'){
                rect = group.addShape('rect', {
                  attrs: {
                    x: -75,
                    y: -25,
                    width: 150,
                    height: 50,
                    radius: 25,
                    stroke: '#5B8FF9',
                    fill: '#B2E98E',
                    lineWidth: 1,
                  },
                  name: 'rect-shape',
                });
              }
              else {
                rect = group.addShape('rect', {
                  attrs: {
                    x: -75,
                    y: -25,
                    width: 150,
                    height: 50,
                    radius: 10,
                    stroke: '#5B8FF9',
                    fill: '#C6E5FF',
                    lineWidth: 1,
                  },
                  name: 'rect-shape',
                });
              }
              if (cfg.name) {
                //this.$console.log('cfg===== ',cfg)
                if(parseInt(cfg.id) % 2 == 0)
                {
                  group.addShape('text', {
                    attrs: {
                      text: cfg.name,
                      x: 0,
                      y: 0,
                      fill: '#00287E',
                      fontSize: 14,
                      textAlign: 'center',
                      textBaseline: 'middle',
                      fontWeight: 'bold',
                    },
                    name: 'text-shape',
                  });
                }
                else{
                  group.addShape('text', {
                    attrs: {
                      text: cfg.name,
                      x: 0,
                      y: 0,
                      fill: '#000000',
                      fontSize: 14,
                      textAlign: 'center',
                      textBaseline: 'middle',
                      fontWeight: 'bold',
                    },
                    name: 'text-shape',
                  });
                }
              
              }
              return rect;
            },
          },
          'single-node',
        );

        G6.registerBehavior('click-select', {
          getEvents() {
            return {
              'node:click': 'onNodeClick'
            };
          },
          onNodeClick(evt) {
            // 判断是否是子流程，如果是则打开子流程的流程图
            if(evt.item._cfg.model.isSubFlow === '1' && evt.item._cfg.model.subFlowId){
              // 获取子流程的信息
              //this.$console.log('evt.item._cfg.model.subFlowId ====',evt.item._cfg.model.subFlowId)
              let subFlowId = evt.item._cfg.model.subFlowId;
              const loading = _self.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading'
              });
              let reqParams =  {
                singleBody: {
                  id: subFlowId
                }
              }
              let commonData = reqCommonMsg(reqParams)
              getFlowChartData(commonData).then(res => {
                _self.subFlowInfo.subFlowData.push(res.data.body.flowArea.flowExtData);
                _self.subFlowInfo.subFlowChartDialogMap[_self.subFlowInfo.subFlowContainerList[index+1]] = true;
                loading.close();
              }, error => {
                //this.$console.log(error);
                loading.close();
              });
            }
          },
        });

        const width = document.getElementById(subFlowContainer).scrollWidth;
        const height = document.getElementById(subFlowContainer).scrollHeight || 400;
        this.subFlowInfo.graphList[index] = new G6.Graph({
          animate: true,
          fitView: true,
          container: subFlowContainer,
          width,
          height,
          layout: {
            type: 'dagre',
            rankdir: 'LR',
            align: 'UL',
            nodesepFunc: d => {
              if (d.id === '3') {
                return 100;
              }
              return 50;
            },
            ranksep: 70,
            controlPoints: true
          },
          defaultNode: {
            type: 'sql',
          },
          defaultEdge: {
            type: 'polyline',
            style: {
              radius: 20,
              offset: 45,
              endArrow: true,
              lineWidth: 2,
              stroke: '#C2C8D5',
            },
          },
          nodeStateStyles: {
            selected: {
              stroke: '#d9d9d9',
              fill: '#5394ef',
            }
          },
          modes: {
            default: [
              'drag-canvas',
              'zoom-canvas',
              'click-select',
              {
                type: 'tooltip',
                formatText(model) {
                  const cfg = model.conf;
                  const text = [];
                  cfg.forEach(row => {
                    text.push(row.label + ':' + row.value + '<br>');
                  });
                  return text.join('\n');
                },
                offset: 30
              },
            ],
          }
        });
      }
      this.subFlowInfo.graphList[index].data(data);
      this.subFlowInfo.graphList[index].render();
      this.subFlowInfo.subFlowChartsLoading = true;
      loading.close();
    },
    /**
     * 关闭子流程图
     */
    closeSubFlow(subFlowContainer, index){
      this.subFlowInfo.subFlowChartDialogMap[subFlowContainer] = false;
      //this.$console.log('1closeSubFlow====》', this.subFlowInfo.subFlowData)
      this.subFlowInfo.subFlowData.pop();
      // this.subFlowInfo.graph.destroy();
      //this.$console.log('2closeSubFlow====》', this.subFlowInfo.subFlowData)
    }
  }
}
</script>

<style>
.g6-tooltip {
    border-radius: 6px;
    font-size: 12px;
    color: #fff;
    background-color: #000;
    padding: 2px 8px;
    text-align: center;
  }
</style>